package com.rockywong.springcloud.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by rockywong on 2018/7/31.
 */
@RestController
public class IndexController {

    @Autowired
    private LoadBalancerClient balancerClient;

    @GetMapping("/lbc/show")
    public String show() {
        // 选择服务
        ServiceInstance serviceInstance = balancerClient.choose("eureka-client");

        // 生成URL
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/show";

        RestTemplate restTemplate = new RestTemplate();
        String r = restTemplate.getForObject(url, String.class);
        if(StringUtils.isEmpty(r)) {
            r = url;
        } else {
            r = r + "\n URL: " + url;
        }
        return r;
    }
}
